<?php

namespace App\Kuafu\Mqtt\Service;


use App\Kuafu\Mqtt\Enum\MqttCodeEnum;
use App\Kuafu\Mqtt\Model\Queue;
use App\Kuafu\Order\Service\OrderService;
use App\Kuafu\Shop\Enum\ShopCacheEnum;
use App\Kuafu\Shop\Jobs\BatchSendMenuJob;
use App\Kuafu\WaiMai\Enum\WaiMaiCacheEnum;
use App\Kuafu\WaiMai\Service\WaiMaiOrderService;
use App\Support\MQTT;
use App\Kuafu\Base\Service\BaseService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;

class MqttQueueService extends BaseService
{

    // 更新菜单 MQTT QUEUE Redis Key
    public const REDIS_UPDATE_PRODUCT_MENU_KEY = 'redis_update_product_menu_key';

    /**
     * 更新菜单 MQTT QUEUE
     */
    public static function updateProductMenu(array $shopIds)
    {
        $times        = 1;
        $shardingNums = 3;

        $loopShopData = [];
        foreach ($shopIds as $shopId) {
            $uuid = Str::uuid()->toString();
            $key  = MqttQueueService::REDIS_UPDATE_PRODUCT_MENU_KEY . $shopId;
            Redis::set($key, $uuid, 'ex', 86400);

            $loopShopData[] = [
                'shopId' => $shopId,
                'uuid'   => $uuid
            ];

            if (count($loopShopData) >= $shardingNums) {
                self::dispatchUpdateProductMenu($loopShopData, $times);
                $loopShopData = [];
                ++$times;
            }
        }

        self::dispatchUpdateProductMenu($loopShopData, $times);
    }

    private static function dispatchUpdateProductMenu(array $loopShopData, $times)
    {
        dispatch(function () use ($loopShopData) {
            foreach ($loopShopData as $shopDatum) {
                $shopId    = $shopDatum['shopId'];
                $uuid      = $shopDatum['uuid'];
                $redisUuid = Redis::get(MqttQueueService::REDIS_UPDATE_PRODUCT_MENU_KEY . $shopId);
                if ($redisUuid != $uuid) {
                    return;
                }

                Cache::forget(ShopCacheEnum::getShopInfo($shopId));
                (new MqttService(0, $shopId))->updateProductMenu();
                Log::info('updateMenu :' . $shopId);
            }
        })->onQueue(BatchSendMenuJob::$QUEUE_NAME)->delay($times);
    }

    /**
     * 更新门店商屏 MQ
     *
     * @return void
     */
    public static function updateShopBannerConfig(array $shopIds)
    {
        $times = 1;
        foreach ($shopIds as $shopId) {
            dispatch(function () use ($shopId) {
                // MQTT 推送设备更新配置
                (new MqttService(0, $shopId))->updateDeviceConfig();
                Log::info('updateShopBannerConfig :' . $shopId);
            })->delay($times);
            ++$times;
        }
    }

}
